<template>
  <!-- 通用属性 -->
	<div class="fillcontain">
    <h2>通用属性</h2>
    <!-- 操作按钮 -->
    <el-row>
      <el-col :span="24" class="pb15 pt5">
        <el-button
          type="danger"
          size="mini"
          plain
          @click="addProperty()"
          >新增属性
        </el-button>
        <el-button
          type="danger"
          size="mini"
          style="margin-left: 10px"
          plain
          @click="editProperty()"
          >修改
        </el-button>
        <el-button
          type="danger"
          size="mini"
          style="margin-left: 10px"
          plain
          @click="delProperty()"
          >删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 属性多选框组 -->
    <div class="card">
      <div class="card-title">通用属性</div>
    </div>
    <el-checkbox-group v-model="checkList" style="padding: 0 30px">
      <el-checkbox :label="item.id" v-for="(item,index) in propertyList" :key="index">{{item.propertyName}}</el-checkbox>
    </el-checkbox-group>

    <!-- 弹窗 -->
    <el-dialog
      :title="handleType == 'add'?'新增属性':'修改属性'"
      :visible.sync="propertyVisible"
      v-if="propertyVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="980px"
      center
      >
      <div class="base-mian-cell-title">
        <i></i>
        <span class="tips">基本信息</span>
        </div>
      <el-form ref="propertyForm" :model="propertyForm" label-width="150px" :rules="propertyRules" style="overflow: hidden;">
        <el-col :span="12" class="common-box">
          <el-form-item label="属性编码：">
            <el-input disabled v-model="propertyForm.propertyCode" placeholder="系统自动生成" :maxlength="50" @input="inputChange($event,propertyForm,'propertyCode')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="属性名称：" prop="propertyName">
            <el-input v-model="propertyForm.propertyName" :maxlength="20" placeholder="请输入属性名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="是否有效：">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" active-value="1" inactive-value="0" active-text="是" inactive-text="否" v-model="propertyForm.status"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="common-box">
          <el-form-item label="备注：">
            <el-input type="textarea" :rows="3" v-model="propertyForm.remark" :maxlength="400" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-form>

      <div class="base-mian-cell-title">
        <i></i>
        <span class="tips">属性分类</span>
      </div>
      <el-table :data="propertyTableData" highlight-current-row header-cell-class-name="table-header-class" style="width: 70%">
          <el-table-column align="center" type="index" width="80" label="序号"></el-table-column>
          <el-table-column align="center" label="分类" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.propertyType" :maxlength="20" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            width="100"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-plus" @click="handleAdd()"></el-button>
              <el-button type="text" size="small" icon="el-icon-delete" @click="handleDel(scope.row,scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>

      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="propertySave">保 存</el-button>
        <el-button @click="propertyReset">取 消</el-button>
      </span>
    </el-dialog>

	</div>
</template>

<script>
  import {
    getGeneralPropertiesApi,
    delGeneralPropertiesApi,
    addOrUpdateGeneralPropertiesApi,
    getCommonInfoApi
  } from "@/api/medicalLibrary/medicalbank";
  import constant from "@/utils/constant";
	export default {
		data() {
       let validatePropertyCode = (rule, value, callback) => {
        let reg = /^[\w]*$/
        if (value && !value.match(reg)) {
          callback(new Error('请输入字母和数字类型'));
        } else {
          callback();
        }
      }
			return {
        checkList: [],
        propertyList: [],

        // 弹窗
        handleType: 'add',  //弹窗类型
        propertyVisible: false,
        propertyForm: {
          propertyCode: '',
          propertyName: '',
          status: '1',
          remark: ''
        },
        propertyRules: {
          propertyCode: [
            { required: true, message: '请输入属性编号', trigger: 'blur' },
            // { validator: validatePropertyCode, trigger: 'blur' }
          ],
          propertyName: [
            { required: true, message: '请输入属性名称', trigger: 'blur' }
          ],
        },
        propertyTableData: [{propertyType: ''}],
      }
		},
		created() {
      this.getPropertyList()
		},
		methods: {
      inputChange(el,row,field){
        let val = el.replace(/[^a-zA-Z\d\-\_]/g,"")
        this.$set(row,field,val)
      },
      // 获取属性列表
      getPropertyList(){
        this.checkList = []
        this.propertyList = []
        this.$store.dispatch("loading/CHANGE_LOADING", true);
        getGeneralPropertiesApi({}).then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if(res.resultCode == constant.SUCCESS) this.propertyList = res.data || []
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
      },
      // 点击新增属性按钮
      addProperty(){
        this.propertyReset()
        this.handleType = 'add'
        this.propertyVisible = true
      },
      // 点击修改按钮
      editProperty(){
        if(!this.checkList.length) {
          this.$message.warning('请先勾选通用属性')
          return
        }
        if(this.checkList.length > 1) {
          this.$message.warning('只能修改单个通用属性')
          return
        }
        
        getCommonInfoApi({id: this.checkList[0]}).then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.resultCode === 0) {
            this.propertyTableData = res.data && res.data.length ? res.data : [{propertyType: ''}]
          }
        }).catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });

        this.handleType = 'edit'
        let filterArr = this.propertyList.filter(item=>item.id == this.checkList[0])
        this.propertyForm = JSON.parse(JSON.stringify(filterArr[0]))
        this.propertyVisible = true
      },
      // 点击删除按钮
      delProperty(){
        if(!this.checkList.length) {
          this.$message.warning('请先勾选通用属性')
          return
        }
        this.$confirm('是否删除选中的通用属性?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delGeneralPropertiesApi({ids: this.checkList}).then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if (res.resultCode === 0) {
              this.$message.success('删除成功')
              setTimeout(()=>{
                this.getPropertyList()
              },500)
            }
          }).catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        })
      },

      // -----弹窗
      // 点击列表的添加按钮
      handleAdd(){
        this.propertyTableData.push({propertyType: ''})
      },
      // 点击列表的删除按钮
      handleDel(row,_index){
        this.propertyTableData.splice(_index,1); 
        if(!this.propertyTableData.length) this.handleAdd()
      },
      // 点击弹窗保存按钮
      propertySave(){
        this.$refs.propertyForm.validate((valid) => {
          if (valid) {
            let newArr = this.propertyTableData.filter(fItem=>fItem.propertyType.trim())
            if(newArr.length < this.propertyTableData.length) {
              this.$message.warning('存在数据为空的属性分类')
              return
            }
            let params = {
              ...this.propertyForm,
              generalCommonValueRelationVos: this.propertyTableData
            }
            this.$store.dispatch("loading/CHANGE_LOADING", true);
            addOrUpdateGeneralPropertiesApi(params).then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.resultCode === 0) {
                this.propertyVisible = false
                this.$message.success(this.handleType == 'add' ? '属性新增成功' : '属性修改成功')
                setTimeout(()=>{
                  this.getPropertyList()
                },500)
              }
            }).catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
          }
        });
      },
      // 点击弹窗取消按钮
      propertyReset(){
        this.propertyVisible = false
        this.propertyTableData = [{propertyType: ''}]
        this.propertyForm = {
          propertyCode: '',
          propertyName: '',
          status: '1',
          remark: ''
        }
      }
		},
	}
</script>

<style lang="less" scoped>
	.fillcontain {
		padding: 20px;
    min-height: calc(100vh - 200px);
  }
  h2{
    font-family: 'PingFangSC-Semibold', 'PingFang SC Semibold', 'PingFang SC', sans-serif;
    font-weight: 650;
    font-style: normal;
    font-size: 18px;
    padding: 0 0 10px 30px;
    margin-bottom: 20px;
    border-bottom: 1px solid #e2e2e2;
    margin-left: -20px;
    margin-right: -20px;
  }
  .card{
    height: 44px;
    border: 1px solid #e2e2e2;
    border-radius: 1px;
    margin-bottom: 30px;
  }
  .card-title{
    height: 42px;
    width: 80px;
    line-height: 42px;
    text-align: center;
    color: #f76767;
    border-bottom: 3px solid #f76767;
    margin-left: 20px;
  }
  .base-mian-cell-title {
    padding: 0 20px;
    margin-bottom: 15px;
    height: 36px;
    background: #f8f8f8;
    line-height: 36px;
    .tips {
      margin-left: 10px;
      font-weight: bold;
      float: left;
    }
    i{
      width: 2px;
      height: 16px;
      float: left;
      background: red;
      margin-top: 10px;
    }
  }
  /deep/ .el-dialog__body{
    overflow: auto;
    max-height: 55vh;
  }
  /deep/ .el-checkbox{
    min-width: 130px;
    margin-bottom: 20px;
  }
  /deep/ .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
}
/*打开时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: -10px;
}
/*关闭时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 20px;
}
/*显示文字*/
/deep/ .tableScopeSwitch .el-switch__label.is-active {
    display: block;
}
/deep/ .tableScopeSwitch.el-switch .el-switch__core,
/deep/ .el-switch .el-switch__label {
    width: 50px !important;    /*开关按钮的宽度大小*/
}
</style>
